#!/bin/bash
version="V1.0"
echo "The script version is $version."
server="http://192.168.50.4:8001/arf9022/release/"

if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root!" 1>&2
   exit 1
fi

if ! [ -x "$(command -v wget)" ]; then
	if [[ -f  /home/avc/wget_1.17.1-1ubuntu1.5_armhf.deb ]]; then
		dpkg -i wget_1.17.1-1ubuntu1.5_armhf.deb &&
		rm wget_1.17.1-1ubuntu1.5_armhf.deb
	else
		echo 'Error: wget is not installed.' >&2
		exit 1
	fi
fi

function update_dts() {
	url=$1
	is_zed=$2
	
	if [ ! -d /mnt/dts ];then 
		mkdir dts
	elif [ -f /mnt/dts/*.dts ];then
		tar -czvf /mnt/dts.tar.gz /mnt/dts/ 1>/etc/null
		rm /mnt/dts/* 2>/etc/null
	fi

	cd /mnt/dts/
	wget -r -np -nd -k $url -P /mnt/dts
	if [ $? -ne 0 ];then
		echo 1
		exit 1
	fi
	
	rm index.html 2>/etc/null
	if [ $is_zed -eq 1 ];then
		rm avc.dts 2>/etc/null
	else 
		rm zedboard.dts 2>/etc/null
	fi
	echo 0
}

iiodev_path="/sys/bus/spi/devices/spi0.0/iio:device0/"
if [ ! -d $iiodev_path ];then
	echo "Count not find iio:device0!"
	exit 1
fi

sw_version=$(cat ${iiodev_path}software_version) >&2
if [[ "$sw_version" = "" ]]
then
	echo "error:canot get Image version"
	exit 1
fi

board=$(cat /proc/device-tree/model) >&2
if [[ $board =~ "ZED" ]]; then
		board="ZedBoard"
		echo "Current board is ZedBoard"
elif [[ $board =~ "ZC706" ]]; then
		board="ZC706"
		echo "Current board is ZC706"
else
		echo "Device tree don't have describe as ZedBoard or ZC706"
		exit 1
fi

echo "Current driver version is V$sw_version."
current_m=${sw_version%"."*}
current_s=${sw_version#*"."}
version_m=0
version_s=0

wget -q ${server} -O .update_devicetree.txt
while read line
do
	if [[ $line =~ "href=\"V" ]]
	then
		sw_m=${line%%"."*}
		sw_m=${sw_m#*"V"}
		sw_s=${line#*"."}
		sw_s=${sw_s%%'/'*}
		sw_s=$((10#$sw_s))
		# echo "$sw_m.$sw_s"
		if ((sw_m > version_m))
		then
			version_m=$sw_m
			version_s=$sw_s
		elif ((sw_m == version_m && sw_s > version_s))
		then
			version_s=$sw_s
		fi
	fi
done < .update_devicetree.txt

rm .update_devicetree.txt

echo "The newest version is V$version_m.$version_s."
read -p "Are you want to update to the newest version? [Y/n]" update_sel
if [[ $update_sel = "Y" ]] || [[ $update_sel = "y" ]] || [[ $update_sel = "" ]]
then
	echo "Update to V$version_m.$version_s devicetree source code"
	if ! mountpoint -q /mnt; then
		mount /dev/mmcblk0p1 /mnt/
	fi
	if [[ $board = "ZedBoard" ]];then
		upstate=`update_dts "${server}V$version_m.$version_s/dts/" 1`			
	else 
		upstate=`update_dts "${server}V$version_m.$version_s/dts/" 0`
	fi

	if [ $upstate -ne 0 ];then
		echo "error:Devicetree upgrade faild!"
		exit 1
	else
		echo "Devicetree update successfully!"
	fi
fi



